<%--
  Created by IntelliJ IDEA.
  User: 62585
  Date: 2021/4/11
  Time: 23:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>员工列表</title>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>


</head>
<body>
<%
    request.setAttribute("ctp", request.getContextPath());
%>

<div class="container">
    <%--  标题  --%>
    <div id="title" class="row">
        <%--     占5列   --%>
        <div class="col-md-5">
            <h1>SSM - CURD</h1>
        </div>
    </div>
    <%--  增删  --%>
    <div id="addDelBtn" class="row">
        <div class="col-md-4 col-md-offset-8">
            <button id="addBtn" type="button" class="btn btn-primary">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                新增
            </button>
            <button id="delBtn" type="button" class="btn btn-danger">
                <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                删除
            </button>
        </div>
    </div>
    <%--  表格  --%>
    <div id="table" class="row">
        <table id="emps_table" class="table table-hover">
            <thead>
            <tr>
                <th><input type="checkbox" class="checkbox_item"></th>
                <th>#</th>
                <th>姓名</th>
                <th>性别</th>
                <th>电子邮件</th>
                <th>部门名</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <%--  底部  --%>
    <div id="bottom" class="row">
        <div id="page_info"></div>
        <div id="navigation"></div>
    </div>

    <!-- 添加内容模态框 -->
    <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">员工添加</h4>
                </div>
                <div class="modal-body">
                    <%--        表单从这里开始            --%>
                    <form class="form-horizontal" id="addForm">
                        <div class="form-group">
                            <label for="inputEmpName" class="col-sm-2 control-label">姓名</label>
                            <div id="nameEditor" class="col-sm-10">
                                <%--                不同的输入格式,只需要修改这一部分就好,其他不要改                --%>
                                <input type="text" class="form-control" id="inputEmpName" name="empName"
                                       placeholder="6-16位 数字字母下划线">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="inputEmpGender1" value="male"
                                           checked="checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="inputEmpGender2" value="female"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmail" class="col-sm-2 control-label">电子邮件</label>
                            <div id="emailEditor" class="col-sm-10">
                                <input type="email" class="form-control" id="inputEmail" name="email"
                                       placeholder="xxx@xxx.com">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputEmailDepartment" class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-6">
                                <select id="inputEmailDepartment" class="form-control" name="deptId">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="submitBtn" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            refresh(1);
        });

        function refresh(pn) {
            $.ajax({
                url: "${ctp}/empsWithJson",
                data: "pn=" + pn,
                type: "GET",
                success: function (data) {
                    build_emps_table(data);
                    build_bottom(data);
                }
            })
        }

        function build_emps_table(data) {
            $("#emps_table tbody").empty();
            var emps = data.extend.pageInfo.list;
            $.each(emps, function (index, item) {
                var checkbox = $("<td><input type='checkbox' class='check_item'/></td>");
                var empId = $("<td></td>").append(item.empId);
                var empName = $("<td></td>").append(item.empName);
                var gender = $("<td></td>").append(item.gender === "male" ? "男" : "女");
                var email = $("<td></td>").append(item.email);
                var deptName = $("<td></td>").append(item.department.deptName);
                var editBtn = $("<button></button>")
                    .addClass("btn btn-info btn-sm edit_btn")
                    .append($("<span></span>")
                        .addClass("glyphicon glyphicon-pencil")
                        .append("修改"));
                editBtn.attr("edit_id", item.empId);

                var deleteBtn = $("<button></button>")
                    .addClass("btn btn-danger btn-sm delete_btn")
                    .append($("<span></span>")
                        .addClass("glyphicon glyphicon-trash")
                        .append("删除"));
                deleteBtn.attr("delete_id", item.empId);
                var btn = $("<td></td>").append(editBtn).append(" ").append(deleteBtn);
                $("<tr></tr>")
                    .append(checkbox)
                    .append(empId)
                    .append(empName)
                    .append(gender)
                    .append(email)
                    .append(deptName)
                    .append(btn)
                    .appendTo("#emps_table tbody");
            });
        }

        function build_bottom(data) {
            var pageInfo = data.extend.pageInfo;
            build_pageInfo(pageInfo);
            build_navigation(pageInfo);
        }

        function build_pageInfo(pageInfo) {
            $("#page_info").empty()
                .addClass("col-md-4 col-md-offset-1")
                .append("当前第")
                .append($("<span></span>")
                    .addClass("label label-default")
                    .append(pageInfo.pageNum))
                .append("页，共有")
                .append($("<span></span>")
                    .addClass("label label-default")
                    .append(pageInfo.pages))
                .append("页，总计")
                .append($("<span></span>")
                    .addClass("label label-default")
                    .append(pageInfo.total))
                .append("条记录")
        }

        function build_navigation(pageInfo) {
            var ul = $("<ul></ul>").addClass("pagination");

            var toFirstPageLi = $("<li></li>")
                .append($("<a></a>").append("首页"));
            var toPrePageLi = $("<li></li>")
                .append($("<a></a>").append("&laquo;"));
            var toPostPageLi = $("<li></li>")
                .append($("<a></a>").append("&raquo;"));
            var toLastPageLi = $("<li></li>")
                .append($("<a></a>").append("尾页"));
            if (pageInfo.isFirstPage) {
                toFirstPageLi.addClass("disabled");
                toPrePageLi.addClass("disabled");
            } else {
                toFirstPageLi.click(function () {
                    refresh(1);
                });
                toPrePageLi.click(function () {
                    refresh(pageInfo.pageNum - 1);
                });
            }

            if (pageInfo.isLastPage) {
                toLastPageLi.addClass("disabled");
                toPostPageLi.addClass("disabled");
            } else {
                toLastPageLi.click(function () {
                    refresh(pageInfo.total);
                });
                toPostPageLi.click(function () {
                    refresh(pageInfo.pageNum + 1);
                });
            }

            // 添加首页和上一页
            ul.append(toFirstPageLi).append(toPrePageLi);
            // 添加页面链接
            $.each(pageInfo.navigatepageNums, function (index, item) {
                var li = $("<li></li>").append($("<a></a>").append(item));
                if (item === pageInfo.pageNum) {
                    li.addClass("active");
                } else {
                    li.click(function () {
                        refresh(item);
                    });
                }
                ul.append(li);
            });
            // 添加下一页和尾页
            ul.append(toPostPageLi).append(toLastPageLi);
            $("#navigation").empty().append(ul);
        }

        // 点击新增触发
        $("#addBtn").click(function () {
            $('#addEmpModal').modal({
                keyboard: true
            });
            getDeps();
        });

        // 查询所有部门信息,并显示在多选框中
        function getDeps() {
            $.ajax({
                url: "${ctp}/deps",
                type: "GET",
                success: function (data) {
                    var select = $("#inputEmailDepartment")
                    var deps = data.extend.deps;
                    $.each(deps, function (index, dep) {
                        select.append($("<option></option>").append(dep.deptName).attr("value", dep.deptId));
                    });
                }
            })
        }

        // 提交按钮
        $("#submitBtn")
            .click(function () {
                // 检查是否已经验证通过
                if ($("#nameEditor").attr("verified") === "false") {
                    return false;
                }
                if ($("#emailEditor").attr("verified") === "false") {
                    return false;
                }

                $.ajax({
                    url: "${ctp}/emp",
                    type: "POST",
                    data: $("#addForm").serialize(),
                    success: function (data) {
                        if (data.code === "success") {
                            $('#addEmpModal').modal("hide"); //隐藏输入框
                            refresh(9999); // 跳转到末页
                        } else {
                            $('#addEmpModal').modal("hide");
                            alert("提交失败");
                        }
                    }
                });
            });

        $("#nameEditor").change(function () {
            if (!data_verify($("#nameEditor"), /^[a-z0-9_-]{6,16}$/, "姓名格式有误")) {
                return false;
            }
            if (!name_verify($("#nameEditor"), "用户名已存在")) {
                return false;
            }
            return true;
        });

        $("#emailEditor").change(function () {
            if (!data_verify($("#emailEditor"), /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/, "邮箱格式有误")) {
                return false;
            }
            return true;
        });


        function data_verify(ele, regx, errorMes) {
            var input = ele.children("input").val();
            if (regx.test(input)) {
                ele.removeClass("has-success has-error").addClass("has-success");
                ele.children("span").text("");
                ele.attr("verified", "true");// 添加一个验证标志位
                return true;
            } else {
                ele.removeClass("has-success has-error").addClass("has-error");
                ele.children("span").text(errorMes);
                ele.attr("verified", "false");// 添加一个验证标志位
                return false;
            }
        }

        function name_verify(ele, errorMes) {
            $.ajax({
                url: "${ctp}/checkEmpName",
                data: ele.children("input").serialize(),
                type: "GET",
                success: function (data) {
                    if (data.code === "success") {
                        ele.removeClass("has-success has-error").addClass("has-success");
                        ele.children("span").text("");
                        ele.attr("verified", "true");// 添加一个验证标志位
                        return true;
                    } else {
                        ele.removeClass("has-success has-error").addClass("has-error");
                        ele.children("span").text(errorMes);
                        ele.attr("verified", "false");  // 添加一个验证标志位
                        return false;
                    }
                }
            })
        }

    </script>

</div>
</body>
</html>
